#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
//#include "../../src/thread.h"
#include <pthread.h>
#include "../../src/semaphores.h"
#include "../../src/types.h"
#include<sched.h>

int total = 0;
semaphore _semaphore;

void * func(void * arg){
  int i;
  for(i = 0; i < 1000; i++){
      P(_semaphore);
      printf("total = %d\n",total);
      total++;
      V(_semaphore);
    }
}

int main(int argc, char **argv){
  int err;
  _semaphore = semaphore_create(1,sched_yield);
  pthread_t thread1, thread2, thread3;
  void *ret1, *ret2, *ret3;
  
  printf("Le main lance les 3 threads\n");
  err = pthread_create(&thread1,NULL, func, "thread 1");
  assert(!err);
  err = pthread_create(&thread2,NULL, func, "thread 2");
  assert(!err);
  err = pthread_create(&thread3,NULL, func, "thread 3");
  assert(!err);

  printf("Le main attend les 3 threads\n");
  err = pthread_join(thread3, &ret3);
  assert(!err);
  err = pthread_join(thread2, &ret2);
  assert(!err);
  err = pthread_join(thread1, &ret1);
  assert(!err);

  printf("total = %d\n",total);

  return 0;
}
